from django.contrib.auth.hashers import get_hasher
from rest_framework import mixins
from rest_framework.generics import UpdateAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from apps.centre.serializers import CenterSerializer, UpdatePasswordSerializers, MyreplyforquestionSerializer, \
    collectedArticleSerializer
from apps.users.models import User


class CenterView(mixins.UpdateModelMixin,mixins.ListModelMixin,GenericViewSet):
    serializer_class = CenterSerializer
    def get_queryset(self):
        username=self.request.user
        users = User.objects.filter(username=username)

        return users
    def list(self, request, *args, **kwargs):
        user = request.user
        serializer = CenterSerializer(user)
        data = serializer.data
        replis = user.replies.filter(type=2)
        data['answer_question'] = MyreplyforquestionSerializer(replis,many=True).data
        data['collected_articles'] = collectedArticleSerializer(user.collected_articles,many=True).data
        return Response(data)

    def update(self, request, *args, **kwargs):
        user =self.request.user
        request.data['username'] = user.username
        serializer = self.get_serializer(user, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

# class CenterForteView(mixins.UpdateModelMixin,GenericViewSet):

class UpdatePasswordView(UpdateAPIView):
    serializer_class = UpdatePasswordSerializers
    def update(self, request, *args, **kwargs):
        username=self.request.user
        instance = User.objects.get(username=username)
        serializer = self.get_serializer(instance, data=request.data)
        serializer.is_valid(raise_exception=True)
        hasher = 'default'
        salt = None
        hasher = get_hasher(hasher)
        salt = salt or hasher.salt()
        serializer.validated_data['password'] = hasher.encode(serializer.validated_data['password'], salt)
        serializer.save()
        return Response(serializer.data)

class Userlabel(APIView):
    def put(self,reqeust):
        user = reqeust.user
        data = reqeust.data
        for label in user.labels.all():
            if label not in data:
                 user.labels.remove(label)
        user.save()
        return Response({
            'message':'修改成功',
            'success':True,
        })